package com.guli.mall.member.controller;

import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import com.alibaba.fastjson.JSON;
import com.guli.common.valid.LoginGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.ApiOperation;

import com.guli.mall.member.entity.MemberEntity;
import com.guli.mall.member.service.MemberService;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.R;


/**
 * 会员
 *
 * @author 罗俊华
 * @email 1007052116@qq.com
 * @date 2020-10-18 18:44:16
 */
@RestController
@RequestMapping("member/member")
public class MemberController {

    @Autowired
    private MemberService memberService;


    @GetMapping("/list/{currentPage}/{size}")
    @ApiOperation("根据当前页和每页显示的记录数来获取member分页列表")
    public R list(@PathVariable("currentPage") Integer currentPage, @PathVariable("size") Integer size, @RequestParam Map<String, Object> params) {
        PageUtils<MemberEntity> page = memberService.queryPage(currentPage, size, params);

        return R.ok().put("page", page);
    }

    @GetMapping("/info/{id}")
    @ApiOperation("根据id获取Member")
    public R info(@PathVariable("id") Long id) {
        MemberEntity member = memberService.getById(id);

        return R.ok().put("member", member);
    }

    @PostMapping("/save")
    @ApiOperation("插入Member（用于注册新用户）")
    public R save(@RequestBody MemberEntity member) throws Exception {
        memberService.checkRepeatAndSave(member);

        return R.ok();
    }

    @PostMapping("/login")
    @ApiOperation("用户登陆")
    public R login(@RequestBody MemberEntity memberEntity){

        MemberEntity memberEntityInDB = memberService.login(memberEntity);

        return R.ok().setData(JSON.toJSONString(memberEntityInDB));
    }

    @PostMapping("/loginFromWeiBoUid")
    @ApiOperation("通过微博的UID进行登陆，如果数据库中没有该用户，那么将该用户添加到数据库")
    public R loginFromWeiBoUid(@RequestBody @Validated(LoginGroup.class) MemberEntity memberEntityFromWeiBo){

        MemberEntity memberEntity = memberService.loginFromWeiBoUid(memberEntityFromWeiBo);

        return R.ok().setData(memberEntity);

    }


    @PostMapping("/update")
    @ApiOperation("根据id更新Member")
    public R update(@RequestBody MemberEntity member) {
        memberService.updateById(member);

        return R.ok();
    }

    @PutMapping("/deleteBatch")
    @ApiOperation("根据id批量删除Member")
    public R delete(@RequestBody Long[] ids) {
        memberService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
